<script>
	import Vue from 'vue'
	import Auth from './libs/wechat.js';
	import Routine from './libs/routine.js';
	import * as UserApi from '@/api/member/user.js';
	import * as api from '@/api/api.js';
	import * as config from "@/api/config.js";
	import * as PatientApi from '@/api/hospital/patient.js';
	import * as UserPatient from './libs/userPatient.js';
	import store from './store/index.js'
	import updateCustomBarInfo from './tuniao-ui/libs/function/updateCustomBarInfo.js'
	export default {
		globalData: {
			isLogin: false,
			initUI: true,
			id: 0,
			spid: 0,
			reg: '',
			code: 0,
			closeing: false,
			config_share: {},
			patientList: [],
			appMenus: {},
			tabbarList: [{
					title: '首页',
					url: '/main/index/index',
					activeIcon: 'home-in-fill',
					inactiveIcon: 'home-capsule',
					activeIconColor: '#e08f2f',
					activeColor: '#e08f2f',
					inactiveIconColor: '#FFFFFF',
					iconSize: 50,
					out: true
				},
				{
					title: '资讯',
					url: '/main/news/list',
					activeIcon: 'image-text-fill',
					inactiveIcon: 'image-text',
					activeColor: '#e08f2f',
					activeIconColor: '#e08f2f',
				},
				{
					title: '我的',
					url: '/main/mine/mine',
					activeIcon: 'my-circle-fill',
					inactiveIcon: 'my-circle',
					activeIconColor: '#e08f2f',
					activeColor: '#e08f2f'
				}
			]
		},
		onLaunch: async function(option) {
			console.log('App Launch')

			// #ifdef H5
			uni.hideTabBar();
			// #endif

			uni.getSystemInfo({
				success: function(e) {
					// #ifndef H5
					// 获取手机系统版本
					const system = e.system.toLowerCase()
					const platform = e.platform.toLowerCase()
					// 判断是否为ios设备
					if (platform.indexOf('ios') != -1 && (system.indexOf('ios') != -1 || system.indexOf(
							'macos') != -1)) {
						Vue.prototype.SystemPlatform = 'apple'
					} else if (platform.indexOf('android') != -1 && (system.indexOf('android') != -1)) {
						Vue.prototype.SystemPlatform = 'android'
					} else {
						Vue.prototype.SystemPlatform = 'devtools'
					}
					// #endif
				}
			})

			// 获取设备的状态栏信息和自定义顶栏信息
			// store.dispatch('updateCustomBarInfo')
			updateCustomBarInfo().then((res) => {
				store.commit('$tStore', {
					name: 'vuex_status_bar_height',
					value: res.statusBarHeight
				})
				store.commit('$tStore', {
					name: 'vuex_custom_bar_height',
					value: res.customBarHeight
				})
			})

			let that = this;

			let res = await Routine.getAppConfig();
			console.table(res);
			if (res.code === 0) {
				res.data.ui.themeColorDark = '#e08f2f';
				this.$store.commit("UPDATE_APPCONFIG", res.data);
				uni.setNavigationBarTitle({
					title: res.data.appTitle
				});
			}

			// await this.getAppMenus();

			// #ifdef H5
			store.commit('$tStore', {
				name: 'vuex_custom_bar_height',
				value: '40'
			})
			let snsapiBase = 'snsapi_base';

			let urlData = location.pathname;

			console.info("H5 that.$store.getters.isLogin:" + that.$store.getters.isLogin)
			// 静默登录的情况一：微信公众号
			if (!that.$store.getters.isLogin && Auth.isWeixin()) {
				const {
					code,
					state,
					scope
				} = option.query;
				console.info("wechat_login option.query")
				console.table(option)
				if (code && code != uni.getStorageSync('snsapiCode') && location.pathname.indexOf(
						'/hosp/login/wechat_login') === -1) {
					// 存储静默授权code
					uni.setStorageSync('snsapiCode', code);
					let spread = that.globalData.spid ? that.globalData.spid : 0;
					Auth.auth(code, state, that.$Cache.get('spread'))
						.then(res => {
							console.table(res)
							uni.setStorageSync('snRouter', decodeURIComponent(decodeURIComponent(option.query
								.back_url)));
							if (res.type === 'register') {
								this.$Cache.set('snsapiKey', res.key);
							}

							// 设置访问令牌
							that.$store.commit('LOGIN', {
								token: res.data.accessToken
							});
							// 设置刷新令牌
							that.$store.commit('REFRESH_LOGIN', {
								refreshToken: res.data.refreshToken
							});
							that.$store.commit("SETUID", res.data.userId);
							that.$store.commit("OPENID", res.data.openid);

							that.$store.commit("UPDATE_USERMENU", res.data.appMenu);

							// 刷新用户信息
							// that.$store.dispatch('USERINFO');

							that.getUserInfo(decodeURIComponent(decodeURIComponent(option.query.back_url)));

						})
						.catch(error => {
							this.$isResolve();
							uni.setStorageSync('snRouter', decodeURIComponent(decodeURIComponent(option.query
								.back_url)));
							console.info("catchcatchcatch this.$Cache.has('snsapiKey'):" + this.$Cache.has(
								'snsapiKey'))
							uni.navigateTo({
								url: '/hosp/login/wechat_login?form=app_catch'
							})
							// if (!this.$Cache.has('snsapiKey')) {
							// 	if (location.pathname.indexOf('/hosp/login/wechat_login') === -1) {
							// 		Auth.oAuth(snsapiBase, option.query.back_url);
							// 	}
							// }
						});
				} else {
					this.$isResolve();
					console.info("app urlData:" + urlData)
					console.info("this.$Cache.has('snsapiKey'):" + this.$Cache.has('snsapiKey'))
					if (!this.$Cache.has('snsapiKey')) {
						if (urlData.indexOf('/hosp/login/wechat_login') === -1) {
							console.info("app snsapiKey")
							// Auth.oAuth(snsapiBase, urlData);
						}
					}
				}
			} else {
				// that.getUserInfo();
				that.getPatient();
				if (option.query.back_url) {
					let snRouter = uni.getStorageSync('snRouter');
					uni.removeStorage({
						key: 'snRouter'
					})
					location.replace(snRouter);
				}
			}


			if (!Auth.isWeixin()) {
				// this.$isResolve()
			}

			// #endif

			// #ifdef MP
			// 静默登录的情况二：微信小程序
			console.info("微信小程序 this.$store.getters.isLogin:" + this.$store.getters.isLogin);
			if (!this.$store.getters.isLogin) {
				let regType = that.globalData.reg ? that.globalData.reg : 0;
				Routine.getCode().then(code => {
					console.info("Routine.getCode:" + code);
					Routine.authUserInfo(code, regType)
						.then(res => {})
				}).catch(res => {
					uni.hideLoading();
				});
			}

			// 扫专有二维码
			if (option.query.hasOwnProperty('scene')) {
				console.info("App Launch scene");
				console.info(option.scene);
				switch (option.scene) {
					case 1047: // 扫描小程序码
					case 1048: // 长按图片识别小程序码
					case 1049: // 手机相册选取小程序码
					case 1001: // 直接进入小程序
						let value = this.$util.getUrlParams(decodeURIComponent(option.query.scene));
						console.info("value:" + value);
						let values = value.split(',');
						if (values.length === 2) {
							let v1 = values[0].split(":");
							if (v1[0] === 'reg') {
								that.globalData.reg = v1[1];
							} else {
								that.globalData.id = v1[1];
							}
							let v2 = values[1].split(":");
							if (v2[0] === 'reg') {
								that.globalData.reg = v2[1];
							} else {
								that.globalData.id = v2[1];
							}
						} else {
							that.globalData.reg = values[0].split(":")[1];
						}
						break;
				}
			}
			// #endif

			// #ifdef MP-WEIXIN
			//更新检测
			if (wx.canIUse('getUpdateManager')) {
				const updateManager = wx.getUpdateManager();
				updateManager && updateManager.onCheckForUpdate((res) => {
					if (res.hasUpdate) {
						updateManager.onUpdateReady(() => {
							uni.showModal({
								title: '更新提示',
								content: '新版本已经准备就绪，是否需要重新启动应用？',
								success: (res) => {
									if (res.confirm) {
										uni.clearStorageSync() // 更新完成后刷新storage的数据
										updateManager.applyUpdate()
									}
								}
							})
						})

						updateManager.onUpdateFailed(() => {
							uni.showModal({
								title: '已有新版本上线',
								content: '小程序自动更新失败，请删除该小程序后重新搜索打开哟~~~',
								showCancel: false
							})
						})
					} else {
						//没有更新
					}
				})
			} else {
				uni.showModal({
					title: '提示',
					content: '当前微信版本过低，无法使用该功能，请更新到最新的微信后再重试。',
					showCancel: false
				})
			}
			// #endif
		},
		onShow: function() {
			console.log('App Show')
		},
		onHide: function() {
			console.log('App Hide')
		},
		methods: {
			async getUserInfo(back_url) {
				let that = this;
				let res = await UserApi.getUserInfo();
				console.table(res);
				if (res.code === 0) {
					if (back_url) {
						location.replace(back_url);
					}
					if (res.data) {
						that.$store.commit("UPDATE_USERINFO", res.data);
						console.info("getUserInfo resPatient-----------resPatient");
						let resPatient = await UserPatient.getUserPatient(this.$store.getters.openid);
					}

					if (res.data && res.data.appMenu && res.data.appMenu.indexTop) {
						that.$store.commit("UPDATE_USERMENU", res.data.appMenu);
					}

					this.$isResolve()
				} else {
					this.$isResolve()
				}
			},
			async getPatient() {
				console.info("this.$store.getters.openid:" + this.$store.getters.openid);
				if (this.$store.getters.openid) {
					if (this.$store.getters.userInfo.id) {
						let res = await UserPatient.getUserPatient(this.$store.getters.openid);
					} else {
						let res = await this.getUserInfo();
					}
					this.$isResolve();
				} else {
					this.$isResolve();
				}
			},
			async getAppMenus() {
				// let that = this;
				// let res = await api.getMenuByRoleCode('hospital_mp');
				// if (res.code === 0) {
				// 	that.globalData.appMenus = res.data;
				// }
			},
		}
	}
</script>

<style lang="scss">
	/* 注意要写在第一行，同时给style标签加入lang="scss"属性 */
	@import './static/css/custom_nav_bar.scss';
	@import './tuniao-ui/index.scss';
	@import './tuniao-ui/iconfont.css';
	@import './static/css/ehealth.scss';
	@import './static/css/chs.css';
	@import './static/css/main.scss';
	/*每个页面公共css */

	// uni-page-wrapper {
	// 	display: block;
	// 	min-height: 100vh;
	// 	position: relative;
	// 	background-color: #f2f7fe !important;
	// 	background: linear-gradient(0deg, #f2f7fe, #e08f2f) !important;
	// }

	// uni-page-body {
	// 	font-size: 14px;
	// 	background-color: #f2f7fe !important;
	// 	background: linear-gradient(0deg, #f2f7fe, #e08f2f) !important;
	// 	color: #333;
	// 	min-height: 100vh;
	// }

	page {
		height: 100%;
		background-color: $dawn-page-bg !important;
		navigation-bar-shadow: false;
		font-size: $dawn-font-size-base;
	}

	// 设置整个项目的背景色
	.page {
		// width: 100%;
		// height: 100%;
		// background-color: #f7f9ff;
		background-color: $dawn-page-bg;
		// background-image: url(static/images/bg.jpg);
		// background-size: 100% 100%;
		// background: linear-gradient(0deg, #f2f7fe, #2067be) !important;
		top: 0;
		left: 0;
		z-index: -2;
		min-height: 100vh;
		font-size: $dawn-font-size-base;
	}

	.page-container {
		position: relative;
		// margin-top: -280px;
		margin-top: - $dawn-top-bg-height;
		// padding: 20rpx 30rpx 40rpx 30rpx;
		padding: $dawn-page-container-padding;
		z-index: 2;
	}

	.top-bg {
		// position: relative;
		background: linear-gradient(0deg, $dawn-page-bg, $dawn-theme-color);
		height: $dawn-top-bg-height;
		// height: 280px;
		width: 100%;
		top: 0;
		z-index: 0;
	}

	.tn-hover-collapse {
		height: auto !important;
	}

	.dawn-bg {
		background-color: $dawn-page-bg !important;
	}

	.tn-bg-dawn {
		background-color: $dawn-theme-color !important;
		color: #ffffff;
	}

	.tn-bg-dawn-dark {
		background-color: $dawn-theme-color-dark !important;
		color: #ffffff;
	}

	.tn-bg-dawn-light {
		background-color: $dawn-theme-color-light !important;
	}

	.tn-main-gradient-dawn {
		background-image: repeating-linear-gradient(175deg, $dawn-theme-color, $dawn-theme-color-dark);
		color: #FFFFFF;
	}

	.tn-main-gradient-dawn--light {
		background-image: repeating-linear-gradient(45deg, $dawn-theme-color-light, $dawn-theme-color-light2);
		color: $dawn-theme-color-dark;
	}

	.tn-main-gradient-money {
		background-color: #CC5A36 !important;
		color: #FFFFFF;
	}

	.tn-main-gradient-success {
		background-color: #28A1BA !important;
		color: #FFFFFF;
	}

	.tn-main-gradient-cyan-dawn {
		background-color: #24BA97 !important;
		color: #FFFFFF;
	}

	.tn-main-gradient-danger {
		background-image: repeating-linear-gradient(175deg, $dawn-color-info, $dawn-color-danger);
		color: #FFFFFF;
	}

	.tn-bg-dawn-gray {
		background-color: $dawn-bg-grey !important;
		color: #000000;
	}

	.tn-color-dawn {
		color: $dawn-theme-color !important;
	}
</style>